package cn.jbolt.ec.member;

import cn.jbolt.base.JBoltBaseService;
import cn.jbolt.common.config.Msg;
import cn.jbolt.common.model.BecMember;
import cn.jbolt.common.model.BecMemberCoupon;
import cn.jbolt.common.model.BecRetailerMemberBalance;
import cn.jbolt.common.model.BecSpreader;
import cn.jbolt.ec.log.OpLogService;
import cn.jbolt.ec.spreader.SpreaderService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import org.json.JSONObject;
import java.util.List;

/**
 * @author xieguo
 * @description 会员逻辑层
 */
public class MemberService extends JBoltBaseService<BecMember> {
    public static final MemberService me=new MemberService();

    @Inject
    OpLogService log;


    @Override
    protected BecMember dao() {
        return new BecMember().dao();
    }

    @Inject
    SpreaderService spreaderService;
    @Inject
    CouponService couponService;
    @Inject
    RetailerMemberBalanceService retailerMemberBalance;
    /**
     * 用户点击关注按钮事件
     * 若该用户第一次关注，则保存用户信息并返回欢迎关注嘉美达商城 并返回商城首页  欢迎关注嘉美达商城  若用户第二次以上关注 则返回欢迎回来 并返回商城首页
     * @param openid
     * @param nickname
     * @return
     */
    public String  saveSubscribeMember(String openid,String nickname){
        BecMember becMember = new BecMember().dao().findFirst("SELECT * FROM bec_member where openid_jmd= ?",openid);
        if(becMember!=null){   //不为空，说明有这个人的信息
            return "欢迎回来";
        }else{   //为空，说明没有这个人的信息
            BecMember member = new BecMember();
            member.setOpenidJmd(openid);
            member.setRegTime(System.currentTimeMillis());
            member.setNickname(nickname);
            member.save();
            return "欢迎关注嘉美达商城";
        }
    }

    /**
     * 用户未关注扫描分销商二维码保存信息
     * @param openid
     * @param nickname
     * @param spreader_id
     * @return
     */
    public String saveSpreaderMember(String openid,String nickname,Integer spreader_id){
        BecSpreader becSpreader = new BecSpreader().dao().findFirst("SELECT * FROM bec_spreader where member_id = ?",spreader_id);
        BecMember becMember = new BecMember().dao().findFirst("SELECT * FROM bec_member where openid_jmd= ?",openid);
        if(becMember!=null){  //不为空，则说明有这个会员的信息，但是还不知道他有没有上线
            if(becMember.getSpreaderId()==null) {   //如果没有上线，则直接更新上线
                becMember.setFrom(becSpreader.getName());
                becMember.setSpreaderId(spreader_id);
                becMember.update();
                return "您已成功绑定分销商.";
            }else{
                return "您已有分销商上线.";
            }
        }else {  // 为空，则需要添加这个member的信息并设置他的上线
            BecMember member = new BecMember();
            System.out.println(" new spreader  "+spreader_id);
            member.setFrom(becSpreader.getName());
            member.setSpreaderId(becSpreader.getMemberId());
            member.setOpenidJmd(openid);
            member.setRegTime(System.currentTimeMillis());
            member.setNickname(nickname);
            member.save();
            return "欢迎来到嘉美达商城.";
        }
    }

    /**
     * 用户有基本信息扫描分销二维码
     * @param openid
     * @param spreader_id
     * @return
     */
    public String saveAleaySpreaderMember(String openid,Integer spreader_id){
        BecSpreader becSpreader = new BecSpreader().dao().findFirst("SELECT * FROM bec_spreader where member_id = ?",spreader_id);
        BecMember becMember = new BecMember().dao().findFirst("SELECT * FROM bec_member where openid_jmd=?",openid);
        if (null==becMember) return "您的信息已失效请重新关注公众号";
        if (becMember.getId().equals(spreader_id))
        {
            return "您不能绑定自己为分销商";
        }
        if(becMember.getSpreaderId() == null){ // 如果为空则说明之前这个人只保存了基本信息，未绑定分销商，现在进行绑定
            becMember.setFrom(becSpreader.getName());
            becMember.setSpreaderId(becSpreader.getMemberId());
            becMember.update();
            return "您已成功绑定分销商";
        }else {   //如果不为空，则说明这个人已经绑定了分销商，不能在进行更改
            return "您已有分销商上线";
        }
    }

    /**
     * 通过openid获取会员信息
     * @param openid
     * @return
     */
    public Integer get_member_info(String openid){
        Kv param=Kv.by("openid_jmd",openid);
        List<BecMember> list =getCommonList(param);
        return list.get(0).getId();
    }

    /**
     * 获取分销商积分
     * @param id
     * @return
     */
    public List<BecMember> get_spreader_credit(Integer id){
        Kv param=Kv.by("id",id);
        return getCommonList("spreader_credit",param);
    }

    /**
     * 获取会员平台余额
     * @param id
     * @return
     */
    public List<BecMember> get_platform_balance(Integer id){
        Kv param=Kv.by("id",id);
        return getCommonList("balance",param);
    }

    /**
     * 获取会员信息
     * @param id
     * @return
     */
    public List<BecMember> get_info(Integer id){
        Kv param=Kv.by("id",id);
        return getCommonList("nickname,mobile,wechat_no,qq",param);
    }

    /**
     * 会员信息修改
     * @param id
     * @param nickname
     * @param mobile
     * @param wechat_no
     * @param qq
     * @return
     */
    public boolean modify_info(Integer id,String nickname,String mobile,String wechat_no,String qq){
        BecMember becMember= new BecMember().dao().findById(id);
        if (nickname!=null) becMember.setNickname(nickname);
        if (mobile!=null) becMember.setMobile(mobile);
        if (wechat_no!=null) becMember.setWechatNo(wechat_no);
        if (qq!=null) becMember.setQq(qq);
        return becMember.update();
    }

    /**
     * 通过openid获得memberid
     * @param openid
     */
    public Integer get_member_id(String openid){
        Kv cond=Kv.by("openid_jmd",openid);
        return getCommonList("id",cond).get(0).getId();
    }

    protected List<BecMemberCoupon> get_coupon(int retailer_id,
                                               int member_id){
        Kv cond = Kv.by("retailer_id",retailer_id).set("member_id",member_id);
        return couponService.getCommonList(cond);

    }

    /**
     * 获取商家余额
     * @param retailer_id
     * @param member_id
     * @return
     */
    protected List<BecRetailerMemberBalance> get_retailer_balance(int retailer_id,
                                                                  int member_id){
        Kv cond = Kv.by("retailer_id",retailer_id).set("member_id",member_id);
        return retailerMemberBalance.getCommonList(cond);

    }

    /**
     * 判断会员是否为分销商
     * @param member_id
     */
    /**
     * 判断会员是否为分销商
     * @param member_id
     */
    public Boolean judge_spreader(Integer member_id){
        Kv cond = Kv.by("member_id",member_id);
        List<BecSpreader> list= spreaderService.getCommonList("*",cond);
        if (!list.isEmpty()){
            return 1 == list.get(0).getAudited();
        }else {
            return false;
        }
    }


    /****************
     *  后台管理方法
     * ****************
     */


    /**
     * 获取管理端主页BecMember
     * @param pageNum
     * @param pageSize
     * @param keywords

     * @return
     */
    public Page<BecMember> get_member_page(Integer pageNum, Integer pageSize,String keywords){
        Kv conf = get_member_KV(keywords,null);
        BecMember becMember_dao = new BecMember().dao();
        return becMember_dao.template("ec.mall.manage.member.get_member_page",conf).paginate(pageNum,pageSize);

    }

    public Long get_member_balance(String keywords){
        Kv conf = get_member_KV(keywords,"sum(balance)");
        return Db.template("ec.mall.manage.member.get_member_page",conf).queryLong();
    }


    public Long get_member_credit(String keywords){
        Kv conf = get_member_KV(keywords,"sum(spreader_credit)");
        return Db.template("ec.mall.manage.member.get_member_page",conf).queryLong();
    }



    public Kv get_member_KV(String keywords,String columns){
        Kv conf = Kv.by("table",table());

        if (keywords != null)
            keywords = keywords.trim();

        conf.setIfNotNull("keywords",keywords);
        conf.setIfNotNull("columns",columns);
        return conf;
    }






//    /**
//     * 得到回收站内商品数量
//     * @return
//     */
//    public  Integer get_delete_count(){
//        return getCount(Kv.by("is_del", true));
//    }


    /**
     * 更新数据
     * @param userId
     * @param becMember
     * @param isUpdateSpreader
     * @param updateSpreader_s
     * @param isUpdateBalance
     * @param updateBalance_s
     * @return
     */
    public Ret update_member(Integer userId, BecMember becMember, Integer isUpdateSpreader, String updateSpreader_s,
                             Integer isUpdateBalance, String updateBalance_s){



        if(becMember==null||notOk(becMember.getId())){
            return fail(Msg.PARAM_ERROR);
        }

        Long oldBalance = becMember.getBalance();
        Integer oldSpreader = becMember.getSpreaderCredit();

        Long newBalance = null;
        Integer newSpreader = null;

        // 把输入进来的金额 转换 成 Integer 和 Long 型
        Long updateBalance =  Integer_by_String(updateBalance_s).longValue();
        Integer updateSpreader = Integer_by_String(updateSpreader_s);

        if ( updateBalance != null && updateBalance != 0 ){
            if (isUpdateBalance == 1){
                newBalance = becMember.getBalance()+updateBalance;

            }
            else if (isUpdateBalance == 2 ){
                if (becMember.getBalance()<updateBalance)
                    return fail("余额不足");
                newBalance = becMember.getBalance()-updateBalance;
            }
        }

        if (newBalance != null)
            becMember.setBalance(newBalance);

        if ( updateSpreader != null && updateSpreader != 0){
            if (isUpdateSpreader == 1){
                newSpreader = becMember.getSpreaderCredit()+updateSpreader;

            }
            else if (isUpdateSpreader == 2 ){
                if (becMember.getSpreaderCredit()<updateSpreader)
                    return fail("积分不足");
                newSpreader= becMember.getSpreaderCredit()-updateSpreader;
            }
        }
        if (newSpreader != null)
            becMember.setSpreaderCredit(newSpreader);
        JSONObject jo = new JSONObject();
        Db.tx(()->{
            boolean success = becMember.update();
            if (success){
                if (updateBalance != null){
                    log.add_log(log.TYPE_BALANCE,oldBalance.toString(),becMember.getBalance().toString(),userId,table(),becMember.getId());
                    jo.put("status",1);
                }
                if (updateSpreader !=null){
                    log.add_log(log.TYPE_SPREADER,oldSpreader.toString(),becMember.getSpreaderCredit().toString(),userId,table(),becMember.getId());

                }
                jo.put("status",1);
                return true;
            }
            jo.put("status",0);
            return false;
        });
        System.out.println(jo);
        if (jo.get("status").equals(1) )
            return SUCCESS;
        return FAIL;

    }

//    /**
//     * 删除 或 还原商品
//     * @param id
//     * @return
//     */
//    public Ret delete_or_restore_member(Integer userId, Integer id,Integer is_del) {
//        if(notOk(id)){return fail(Msg.PARAM_ERROR);}
//        BecMember becMember=findById(id);
//        if(becMember==null){return fail(Msg.DATA_NOT_EXIST);}
//        becMember.setIsDel(is_del);
//        boolean success=becMember.update();
//        if(success){
//            //添加日志
//            return SUCCESS;
//        }
//        return FAIL;
//    }



    public Integer Integer_by_String(String s){
        Double s_double = Double.parseDouble(s);
        s_double = s_double *100;
        return s_double.intValue();
    }


}
